package com.xgs.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgs.common.core.domain.model.LoginUser;
import com.xgs.common.exception.ServiceException;
import com.xgs.common.utils.DateUtils;
import com.xgs.common.utils.StringUtils;
import com.xgs.common.utils.bean.BeanValidators;
import com.xgs.common.utils.uuid.IdUtils;
import com.xgs.system.domain.Lane;
import com.xgs.system.domain.Roster;
import com.xgs.system.mapper.LaneMapper;
import com.xgs.system.mapper.RosterMapper;
import com.xgs.system.service.RosterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.Arrays;
import java.util.List;

/**
 * @author JerryLu
 * @date 2024/10/23 11:01
 * @description 名单信息Service业务层处理
 */
@Service
public class RosterServiceImpl extends ServiceImpl<RosterMapper, Roster> implements RosterService {
    @Autowired
    protected Validator validator;
    @Autowired
    private RosterMapper rosterMapper;
    @Autowired
    private LaneMapper laneMapper;

    @Override
    public List<Roster> queryList(Roster roster) {
        QueryWrapper<Roster> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(roster.getDeptId())) {
            queryWrapper.eq("dept_id", roster.getDeptId());
        }
        if (StringUtils.isNotEmpty(roster.getVehicleId())) {
            queryWrapper.like("vehicle_id", roster.getVehicleId());
        }
        if (StringUtils.isNotEmpty(roster.getBasicId())) {
            queryWrapper.eq("basic_id", roster.getBasicId());
        }
        if (StringUtils.isNotEmpty(roster.getBeginRoadNo())) {
            queryWrapper.eq("begin_road_no", roster.getBeginRoadNo());
        }
        if (StringUtils.isNotEmpty(roster.getEndRoadNo())) {
            queryWrapper.eq("end_road_no", roster.getEndRoadNo());
        }
        if (StringUtils.isNotEmpty(roster.getEnStationId())) {
            queryWrapper.eq("en_station_id", roster.getEnStationId());
        }
        if (StringUtils.isNotEmpty(roster.getExStationId())) {
            queryWrapper.eq("ex_station_id", roster.getExStationId());
        }
        if (StringUtils.isNotEmpty(roster.getEnStationHex())) {
            queryWrapper.eq("en_station_hex", roster.getEnStationHex());
        }
        if (StringUtils.isNotEmpty(roster.getExStationHex())) {
            queryWrapper.eq("ex_station_hex", roster.getExStationHex());
        }
        if (roster.getType() != null) {
            queryWrapper.eq("type", roster.getType());
        }
        return this.list(queryWrapper);
    }

    @Override
    public String importRosters(List<Roster> rosterList, Boolean isUpdateSupport, String deptId, LoginUser user, String basicId) {
        if (StringUtils.isNull(rosterList) || rosterList.size() == 0) {
            throw new ServiceException("导入名单数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Roster roster : rosterList) {
            if (!roster.getVehicleId().contains("_")) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、车牌号: " + roster.getVehicleId() + " 无车牌颜色");
                continue;
            }
            QueryWrapper<Lane> laneQuery = Wrappers.query();
            laneQuery.eq("org_id", deptId);
            try {
                // 验证是否存在这车辆
                QueryWrapper<Roster> query = Wrappers.query();
                query.eq("vehicle_id", formatVehicleId(roster.getVehicleId()));
                query.eq("vehicle_type", roster.getVehicleType());
                query.eq("type", roster.getType());
                if (roster.getType() == 0) {
                    query.eq("begin_road_no", roster.getBeginRoadNo());
                    query.eq("end_road_no", roster.getEndRoadNo());
                } else if (roster.getType() == 1) {
                    query.eq("begin_road_no", roster.getBeginRoadNo());
                    query.eq("ex_station_id", roster.getExStationId());
                    query.eq("ex_station_hex", roster.getExStationHex());
                } else if (roster.getType() == 2) {
                    query.eq("en_station_id", roster.getEnStationId());
                    query.eq("en_station_hex", roster.getEnStationHex());
                    query.eq("ex_station_id", roster.getExStationId());
                    query.eq("ex_station_hex", roster.getExStationHex());
                    laneQuery.in("id", Arrays.asList(roster.getEnStationId(), roster.getExStationId()));
                    laneQuery.in("station_hex", Arrays.asList(roster.getEnStationHex(), roster.getExStationHex()));
                } else if (roster.getType() == 3) {
                    query.eq("en_station_id", roster.getEnStationId());
                    query.eq("en_station_hex", roster.getEnStationHex());
                    query.eq("end_road_no", roster.getEndRoadNo());
                }
                query.eq("dept_id", deptId);
                Roster u = rosterMapper.selectOne(query);
                List<Lane> l = laneMapper.selectList(laneQuery);
                if (l.isEmpty()) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、车牌号: " + roster.getVehicleId() + " 对应收费站不属于" + user.getUser().getNickName());
                    continue;
                }
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, roster);
                    roster.setId(IdUtils.fastSimpleUUID());
                    roster.setDeptId(deptId);
                    roster.setBasicId(basicId);
                    roster.setCreateTime(DateUtils.getNowDate());
                    roster.setVehicleId(formatVehicleId(roster.getVehicleId()));
                    if (!roster.getBeginRoadNo().isEmpty() && roster.getBeginRoadNo().length() != 3) {
                        roster.setBeginRoadNo(String.format("%03d", Integer.parseInt(roster.getBeginRoadNo().substring(0, Math.min(roster.getBeginRoadNo().length(), 3)))));
                    }
                    if (!roster.getEndRoadNo().isEmpty() && roster.getEndRoadNo().length() != 3) {
                        roster.setEndRoadNo(String.format("%03d", Integer.parseInt(roster.getEndRoadNo().substring(0, Math.min(roster.getEndRoadNo().length(), 3)))));
                    }
                    if (!roster.getEnStationId().isEmpty() && roster.getEnStationId().length() != 7) {
                        roster.setEnStationId(String.format("%07d", Integer.parseInt(roster.getEnStationId().substring(0, Math.min(roster.getEnStationId().length(), 7)))));
                    }
                    if (!roster.getExStationId().isEmpty() && roster.getExStationId().length() != 7) {
                        roster.setExStationId(String.format("%07d", Integer.parseInt(roster.getExStationId().substring(0, Math.min(roster.getExStationId().length(), 7)))));
                    }

                    rosterMapper.insert(roster);
                    if (roster.getIsDouble() == 1 && roster.getType() == 2) {
                        Roster ros = JSON.parseObject(JSON.toJSONString(roster), Roster.class);
                        ros.setId(IdUtils.fastSimpleUUID());
                        ros.setCreateTime(DateUtils.getNowDate());
                        ros.setDeptId(deptId);
                        ros.setSpare3(0);
                        ros.setEnStationId(roster.getExStationId());
                        ros.setEnStationHex(roster.getExStationHex());
                        ros.setExStationId(roster.getEnStationId());
                        ros.setExStationHex(roster.getEnStationHex());
                        ros.setVehicleId(formatVehicleId(roster.getVehicleId()));
                        rosterMapper.insert(ros);
                    }
                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、车牌号 " + roster.getVehicleId() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, roster);
                    roster.setId(u.getId());
                    roster.setUpdateTime(DateUtils.getNowDate());
                    roster.setVehicleId(formatVehicleId(roster.getVehicleId()));
                    rosterMapper.updateById(roster);
                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、车牌号 " + roster.getVehicleId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、车牌号: " + roster.getVehicleId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、车牌号: " + roster.getVehicleId() + " 导入失败";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
//            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }

    /**
     * 车牌格式化，转大写，去除车牌中的"."(军车、武警车会有的情况)
     *
     * @param vehicleId
     * @return
     */
    private String formatVehicleId(String vehicleId) {
        return vehicleId.toUpperCase().replace(".", "").trim();
    }
}
